<template>
	<view class="sign-box">
		<view class="sign-img-box">
			<image class="sign-img" :src="src" @click="showDrawer"></image>
		</view>
		<button size="mini" type="primary" @click="showDrawer">签名</button>
		<uni-drawer ref="drawer" mode="right" :width="width" :mask-click="false">
			<canvas class="hua-bu" :style="{ width: `${width}px`, height: `${height}px` }" canvas-id="hua-bu"
				@touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas>
			<view class="button-box">
				<button @click="close" type="default">关闭</button>
				<button @click="confirm" type="primary">确定</button>
				<button @click="clear" type="warn">清空</button>
			</view>
		</uni-drawer>
	</view>
</template>

<script setup>
	import {
		ref,
		nextTick,
		onMounted,
	} from 'vue';

	const props = defineProps(['src'])
	const emit = defineEmits(['confirm', 'close'])

	const drawer = ref()
	let isDrawing = false;
	let width = ref(300)
	let height = ref(200)
	let x = 0;
	let y = 0;
	let context = null;

	uni.getSystemInfo({
		success: function(res) {
			width.value = res.windowWidth
			height.value = res.windowHeight - 100
		}
	});


	const touchstart = (e) => {
		x = e.changedTouches[0].x;
		y = e.changedTouches[0].y;
		isDrawing = true;
	}

	const touchmove = (e) => {
		if (isDrawing) {
			drawLine(context, x, y, e.changedTouches[0].x, e.changedTouches[0].y);
			x = e.changedTouches[0].x;
			y = e.changedTouches[0].y;
		}
	}

	const touchend = (e) => {
		if (isDrawing) {
			drawLine(context, x, y, e.changedTouches[0].x, e.changedTouches[0].y);
			x = 0;
			y = 0;
			isDrawing = false;
		}
	}

	function drawLine(context, x1, y1, x2, y2) {
		context.beginPath();
		context.setStrokeStyle('#000000');
		context.setLineWidth(1);
		context.moveTo(x1, y1);
		context.lineTo(x2, y2);
		context.stroke();
		context.closePath();
		context.draw(true)
	}

	const clear = () => {
		context.clearRect(0, 0, width.value, height.value)
		context.draw(true)
	}

	const close = () => {
		drawer.value.close()
		
		emit('close')
	}

	const confirm = () => {
		uni.canvasToTempFilePath({
			canvasId: 'hua-bu',
			success: function(res) {
				emit('confirm', res.tempFilePath)
				emit('close')
			}
		})

		drawer.value.close()
	}

	const showDrawer = () => {
		drawer.value.open()

		nextTick(() => {
			context = uni.createCanvasContext('hua-bu');
		})
	}
</script>

<style scoped>
	.sign-box {
		display: inline-flex;
		align-items: start;
	}

	.hua-bu {
		box-sizing: border-box;
		border: 1px solid #cacaca;
	}

	.sign-img-box {
		width: 400rpx;
		height: 200rpx;
		margin-right: 10rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border: 1px solid #cacaca;
	}

	.sign-img {
		width: 200rpx;
		height: 400rpx;
		transform: rotateZ(-90deg);
	}

	.button-box {
		display: flex;
		margin-top: 5px;
	}

	.button-box button {
		transform: rotateZ(90deg);
		transform-origin: left center;
	}
</style>